#!/usr/bin/python
# -*- coding: utf-8 -*-
import commands
import random
import stat
import sys
import os

reload(sys)
sys.setdefaultencoding('utf8')


def addslashes(string):
    if string.find('\\') >= 0:
        string = string.replace('\\', '')
    if string.find("'") >= 0:
        string = string.replace("'", "\\'")
        # string = string.replace("\\\\'", "\\'")
    if string.find('"') >= 0:
        string = string.replace('"', '\\"')
        # string = string.replace('\\\\"', '\\"')
    return string


def cmd_mix(shell_cmd):
    cmd = "echo exec('" + addslashes(shell_cmd) + "');"
    cmd = '''php7 -r "''' + cmd + '''"'''
    try:
        res = commands.getoutput(cmd)
    except:
        cmd = '''php -r "''' + cmd + '''"'''
        res = commands.getoutput(cmd)
    return res


def path_is_py(exe_file_path):
    arr = exe_file_path.split('.')
    if arr[-1:] == 'py':
        return True
    else:
        return False


def py_specail(exe_file_path):
    add_string = '''
import sys
import os
path = os.path.dirname(os.path.abspath(sys.argv[0]).replace('\\\\', '/')) + '/'
for i in range(1, len(path.split('/')) - 2):
    sys.path.append(path + '../' * i)
'''
    exe_file = open(exe_file_path, 'r')
    lines = []
    for line in exe_file:
        if line.startswith('import sys'):
            continue
        elif line.startswith('import os'):
            continue
        elif line.startswith('path = os.path.dirname'):
            continue
        elif line.startswith('for i in range(1, len(path.spl'):
            continue
        elif line.startswith('    sys.path.append(pa'):
            continue
        else:
            lines.append(line)
    content = add_string + ''.join(lines)
    exe_file.close()
    exe_file = open(exe_file_path, 'w')
    exe_file.write(content)
    exe_file.close()


def cmd_tmp(shell_cmd):
    cmd = addslashes(shell_cmd)
    cmdArr = cmd.split(' ')
    exe_file_path = os.path.abspath(cmdArr[2]).replace('\\', '/')

    if path_is_py(exe_file_path):
        py_specail(exe_file_path)

    file_content = '''
#!/bin/sh
. /etc/profile
. ~/.bash_profile
''' + cmd
    path = '/tmp/r_' + str(random.random())
    f = open(path, 'w')
    f.write(file_content)
    f.close()
    os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
    res = {'code': 1}
    try:
        res = commands.getoutput("sh " + path)
    except:
        print path
    finally:
        os.remove(path)
        return res


class Task(object):
    def __init__(self):
        self.file = None
        self.cmd = None
        self.check_cmd = None
        self.init()
        self.run()

    def init(self):
        try:
            self.file = sys.argv[1]
        except:
            print 'no path'
            exit()
        try:
            self.cmd = sys.argv[2]
        except:
            self.cmd = 'check'
        self.check_cmd = 'ps -ef | grep ' + self.file + '| grep -v grep | grep -v service | grep -v Linux_task |' \
                                                        ' grep -v source '

    def run(self):
        getattr(self, self.cmd)()

    def restart(self):
        self.stop()
        self.start()

    def stop(self):
        cmd = self.check_cmd + '| awk \'{print $2}\' | xargs kill -9'
        cmd_mix(cmd)
        print 'stop ok'

    def get_start_cmd(self, exe):
        cmd = 'nohup ' + exe + ' ' + self.file + " &> " + self.file + "_.log &"
        return cmd

    def start(self):
        ext = self.file.split('.')[-1]
        cmdArr = []
        cmd = ''
        res = ''
        if ext == 'php':
            cmdArr.append(self.get_start_cmd('php'))
            cmdArr.append(self.get_start_cmd('php7'))
        elif ext == 'py':
            cmdArr.append(self.get_start_cmd('python'))
            cmdArr.append(self.get_start_cmd('python3'))

        while len(cmdArr):
            try:
                cmd = cmdArr.pop()
                res = cmd_tmp(cmd)
                break
            except:
                continue

        if not res:
            print('start ok:' + cmd)
        else:
            print 'start fail'
            exit()

    def check(self):
        res = cmd_mix(self.check_cmd)
        if not res:
            self.restart()
        else:
            print res


Task()
